package com.ruoyi.wecom.controller;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.oss.entity.UploadResult;
import com.ruoyi.oss.factory.OssFactory;
import com.ruoyi.oss.service.IOssStrategy;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Objects;

@Api(value = "企微临时文件上传api", tags = {"企微临时文件上传api"})
@AllArgsConstructor
@Slf4j
@RestController
@RequestMapping("/wecom/file")
public class WecomFileUploadController {

    @Resource
    private WxCpService wxCpService;

    /**
     * 上传企业微信临时素材 来群欢迎语消息封面
     *
     * @param file
     * @return
     * @throws IOException
     */
    @ApiOperation("企微临时文件上传用于生成小程序消息封面图片")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "file", value = "文件", paramType = "query", dataTypeClass = File.class, required = true)
    })
    @PostMapping("/upload")
    public R<WxMediaUploadResult> sysWecomUpload(@RequestPart("file") MultipartFile file) throws IOException, WxErrorException {
        WxMediaUploadResult upload = wxCpService.getMediaService().upload(WxConsts.MediaFileType.IMAGE, file.getInputStream(), file.getOriginalFilename());
        String suffix = StringUtils.substring(file.getOriginalFilename(), Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf("."), file.getOriginalFilename().length());
        IOssStrategy storage = OssFactory.instance();
        UploadResult uploadResult;
        try {
            uploadResult = storage.uploadSuffix(file.getBytes(), suffix, file.getContentType());
        } catch (IOException e) {
            throw new ServiceException(e.getMessage());
        }
        String url = uploadResult.getUrl();
        upload.setUrl(url);
        return R.ok(upload);
    }

}
